//
//  NSString+MMAdd.m
//  oc_demo
//
//  Created by haigui on 2021/8/5.
//

#import "NSString+MMAdd.h"

@implementation NSString (MMAdd)

/// 根据字符串内容计算宽高
/// @param font 文本的字体
/// @param maxTextSize 最大宽高
- (CGSize)boundingRectWithfont:(UIFont *)font maxTextSize:(CGSize)maxTextSize{
    CGSize size = [self boundingRectWithSize:maxTextSize options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:font} context:nil].size;
    return CGSizeMake(ceil(size.width), ceil(size.height));
}

///替换空指针为空字符串
+ (NSString *)stringByReplaceNullString:(NSString *)string{
    return string.length?string:@"";
}

/// 字符串转date 默认格式 yyyy-MM-dd HH:mm:ss
- (NSDate *)formatterToDate{
    NSString *formatter = @"yyyy-MM-dd HH:mm:ss";
    if ([self containsString:@"-"]) {
        formatter = @"yyyy-MM-dd HH:mm:ss";
    }else if ([self containsString:@"/"]){
        formatter = @"yyyy/MM/dd HH:mm:ss";
    }else{
        
    }
    return [self formatterToDate:formatter];
}

/// 字符串转date
- (NSDate *)formatterToDate:(NSString *)formatter{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = formatter;
    return [dateFormatter dateFromString:self];
}

/// 去掉字符串两边的空格
- (NSString *)stringByTrimingWhitespace{
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

/// 是否全是数字
- (BOOL)isNumberStr{
    NSScanner* scan = [NSScanner scannerWithString:self];
    int val;
    return [scan scanInt:&val] && [scan isAtEnd];
}

/// 安全化手机号 155xxxx5555
- (NSString *)telphoneSecurity{
    if (self.length != 11 || ![self isNumberStr]) {
        return self;
    }
    return [self stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"xxxx"];
}

/// 检查电话号码格式 1开头  11位数字
- (BOOL)isTelphoneFormat{
    return [self hasPrefix:@"1"] && [self isNumberStr] && self.length == 11;
}

/// 张大炮 => 张***炮
- (NSString *)safetyString{
    if (self.length < 2) {
        return self;
    }
    return [self stringByReplacingCharactersInRange:NSMakeRange(1, self.length-2) withString:@"***"];
}

/// 转时间戳
- (double)toTimeStamp{
    return [[self formatterToDate] timeIntervalSince1970];
}

@end
